package com.linkage.linkedlife.ui.service

import android.annotation.SuppressLint
import android.app.KeyguardManager
import android.app.KeyguardManager.KeyguardLock
import android.app.Service
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.os.Handler
import android.os.IBinder
import android.os.PowerManager
import android.os.PowerManager.WakeLock
import android.util.Log
import android.widget.Toast
import com.linkage.linkedlife.model.MessageEvent
import com.linkage.linkedlife.utils.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


class MyService : Service() {
    private var km: KeyguardManager? = null
    private var kl: KeyguardLock? = null
    private var pm: PowerManager? = null
    private var wl: WakeLock? = null
    private var runnable: Runnable? = null
    private var pollingUtil: PollingUtil? = null
    private var startTimes: String? = null
    private var endTimes: String? = null

    override fun onBind(intent: Intent): IBinder {
        TODO("Return the communication channel to the service.")
    }

    override fun onCreate() {
        super.onCreate()
        val d = Log.d("clark", "startService" + System.currentTimeMillis())
        EventBus.getDefault().register(this)
        EventBus.getDefault().post(MessageEvent("startOk"))
        //每3秒打印一次日志
        pollingUtil = PollingUtil(Handler(mainLooper))

        startTimes =
            (SharedPreferencesUtil.getString(this, "startTime", "08:15:00")).substring(0, 6)
        endTimes =
            (SharedPreferencesUtil.getString(this, "endTime", "17:35:00")).substring(0, 6)

        Log.d("clark", "startTimes=$startTimes-----endTimes=$endTimes")

        val thread = Thread {
            while (true) {
                try {
                    EventBus.getDefault()
                        .post(MessageEvent("-- 正在运行--" + DateTimeUtil.currentTimeWithoutYear))
                    Thread.sleep(10000)
                    Log.e(
                        "Service",
                        "----------handler 定时轮询任务----------" + DateTimeUtil.currentTimeWithoutYear
                    )

                    var s: String = DateTimeUtil.currentTimeWithoutYear;

                    if (s.contains(startTimes!!) || s.contains(endTimes!!)) {
//              wakeUpScreen(this, "clark")
                        wakeAndUnlock(true)
                        openRimet(this)

                    }
                } catch (e: InterruptedException) {
                    e.printStackTrace()
                }
            }
        }
//        thread.start()


        runnable = Runnable {
            Log.e(
                "Service",
                "----------handler 定时轮询任务----------" + DateTimeUtil.currentTimeWithoutYear
            )
            EventBus.getDefault()
                .post(MessageEvent("-- 正在运行--" + DateTimeUtil.currentTimeWithoutYear))
            var s: String = DateTimeUtil.currentTimeWithoutYear;

            if (s.contains(startTimes!!) || s.contains(endTimes!!)) {
//              wakeUpScreen(this, "clark")
                wakeAndUnlock(true)
                Thread.sleep(1000)
                openRimet(this)
//                EventBus.getDefault()
//                    .post(MessageEvent("open"))
            }

        }
        pollingUtil!!.startPolling(runnable!!, 1000, true)


//        openRimet(this)
    }


    fun openRimet(context: Context): Boolean {
        val packageManager = context.packageManager
        val pi: PackageInfo?
        val packageName = "com.alibaba.android.rimet"
        pi = try {
            packageManager.getPackageInfo(packageName, 0)
        } catch (e: PackageManager.NameNotFoundException) {
            //TODO 未安装钉钉
            return false
        }
        val resolveIntent = Intent(Intent.ACTION_MAIN, null)
        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER)
        resolveIntent.setPackage(pi?.packageName)
        val apps =
            packageManager.queryIntentActivities(resolveIntent, 0)
        val resolveInfo = apps.iterator().next()
        if (resolveInfo != null) {
            val className = resolveInfo.activityInfo.name
            val intent = Intent(Intent.ACTION_VIEW)
            intent.addCategory(Intent.CATEGORY_LAUNCHER)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            val cn = ComponentName(packageName, className)
            intent.component = cn
            context.startActivity(intent)
            return true
        } else {
            //TODO resolveInfo = null
            return false
            Log.d("clark", "启动失败")
        }
    }

    private fun wakeUpScreen(context: Context, tag: String) {
        val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager
        //是否需要亮屏唤醒屏幕
        if (!powerManager.isInteractive) {
            val pm = context.getSystemService(Context.POWER_SERVICE) as PowerManager
            val wl = pm.newWakeLock(
                PowerManager.ACQUIRE_CAUSES_WAKEUP or PowerManager.SCREEN_DIM_WAKE_LOCK,
                tag
            )
            wl.acquire(10 * 1000L /*1 minutes*/)
            wl.release()
        }
    }

    @SuppressLint("InvalidWakeLockTag", "WakelockTimeout")
    private fun wakeAndUnlock(b: Boolean) {
        if (b) {
            //获取电源管理器对象
            pm = getSystemService(POWER_SERVICE) as PowerManager

            //获取PowerManager.WakeLock对象，后面的参数|表示同时传入两个值，最后的是调试用的Tag
            wl = pm!!.newWakeLock(
                PowerManager.ACQUIRE_CAUSES_WAKEUP or PowerManager.SCREEN_BRIGHT_WAKE_LOCK,
                "bright"
            )


            //点亮屏幕
            wl?.acquire()

            //得到键盘锁管理器对象
            km = getSystemService(KEYGUARD_SERVICE) as KeyguardManager
            kl = km?.newKeyguardLock("unLock")

            //解锁
            kl?.disableKeyguard()
            Log.d("clark", "解锁屏幕----------------")
        } else {
            //锁屏
            kl?.reenableKeyguard()

            //释放wakeLock，关灯
            wl?.release()
            Log.d("clark", "锁定屏幕----------------")
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
        EventBus.getDefault().post(MessageEvent("stopOk"))
        runnable?.let { pollingUtil!!.endPolling(it) }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGetMessage(message: MessageEvent) {

        when (message.message) {
            "startSet" -> {
                Toast.makeText(this, "重设上班时间成功", Toast.LENGTH_SHORT).show()
                startTimes =
                    (SharedPreferencesUtil.getString(this, "startTime", "08:15:00")).substring(0, 6)
                endTimes =
                    (SharedPreferencesUtil.getString(this, "endTime", "17:35:00")).substring(0, 6)
            }
            "endSet" -> {
                Toast.makeText(this, "重设下班时间成功", Toast.LENGTH_SHORT).show()
                startTimes =
                    (SharedPreferencesUtil.getString(this, "startTime", "08:15:00")).substring(0, 6)
                endTimes =
                    (SharedPreferencesUtil.getString(this, "endTime", "17:35:00")).substring(0, 6)
            }

        }
    }


}